package compile;

import jdk.nashorn.internal.parser.TokenKind;

import java.io.*;

/**
 * @author SongJun
 * @description TODO:
 * @date 2021/9/28 14:24
 */
public class TestSyntaxAnalysis {
    public static void main(String[] args) {
        String program = readFileContent("D:/a.txt");
        //源代码
        System.out.println("源代码:");
        System.out.println(program);

        //词法分析
        System.out.println("\n词法分析结果:");
        Tokenizer tokenizer = new Tokenizer(new CharStream(program));
        Token t = null;
        while((t = tokenizer.peek()).kind != TokenKindEnum.EOF){
            System.out.println(tokenizer.next());
        }
        tokenizer = new Tokenizer(new CharStream(program));  //重置tokenizer,回到开头。

        //语法分析
        Prog prog = new Parser(tokenizer).parseProg();
        System.out.println("\n语法分析后的AST:");
        prog.dump("");

        //语义分析
        new RefResolver().visitProg(prog);
        System.out.println("\n语法分析后的AST，注意自定义函数的调用已被消解:");
        prog.dump("");

        //运行程序
        System.out.println("\n运行当前的程序:");
        Object retVal = new Intepretor().visitProg(prog);
        System.out.println("程序返回值：" + retVal);




    }

    public static String readFileContent(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        StringBuffer sbf = new StringBuffer();
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
        return sbf.toString();
    }
}
